<template>
  <div class="clearfix">
    <el-upload
      :list-type="listType"
      :file-list="fileList"
      :multiple="multiple"
      :before-upload="beforeImageUpload"
      :data="uploadData"
      :http-request="customRequest"
      action=""
      :on-remove="handleRemove"
      :on-preview="handlePreview"
    >
      <div v-if="fileList.length <= limitNum">
        <i class="el-icon-plus"></i>
      </div>
    </el-upload>
    <el-dialog :modal="false"
               :visible="previewVisible"
               :footer="null"
               @close="handleCancel"
    >
      <img style="width: 100%" :src="previewImage" />
    </el-dialog>
  </div>
</template>
<script>
import { fetchUploadImage } from "@/api/system";

export default {
  name: "UploadFileImg",
  props: {
    listType: {
      type: String,
      default: "picture-card",
    },
    fileList: {
      type: Array,
      default: () => [],
    },
    limitNum: {
      type: Number,
      default: 5,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    limitSize: {
      type: Number,
      default: 5,
    },
    fileTypeList: {
      type: Array,
      default: () => [".jpg", ".png"], // [".jpg", ".png", ".rar", ".txt", ".zip", ".doc", ".ppt", ".xls", ".pdf", ".docx", ".xlsx"];
    },
  },
  data() {
    return {
      previewVisible: false,
      previewImage: "",
      uploadData: {
        fileName: null,
        businessId: "",
      },
    };
  },
  methods: {
    beforeImageUpload(file) {
      return new Promise((resolve, reject) => {
        const includeType = this.fileTypeList.find((item) =>
          file.name.includes(item)
        );
        if (!includeType) {
          this.$message.error("请上传jpg/png格式的图片");
          return reject(new Error("请上传jpg/png格式的图片"));
        }
        const limitSize = file.size / 1024 / 1024 < this.limitSize;
        if (!limitSize) {
          this.$message.error(`文件大小不能大于${this.limitSize}MB`);
          return reject(new Error("请上传jpg/png格式的图片"));
        }
        this.uploadData.fileName = file;
        return resolve(true);
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    customRequest({ file }) {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        const formData = new FormData();
        formData.append("fileName", this.uploadData.fileName);
        formData.append("file", fileReader.result);

        fetchUploadImage(formData).then((res) => {
          const obj= {
            ...res.data[0],
            url: res.data[0].absolutePath,
          };
          this.fileList.push(obj);
        });
      };
    },
    handleRemove(file) {
      if(file && file.status==="success"){
        const _index = this.fileList.findIndex((item) => item.originalFileName === file.name);
        this.fileList.splice(_index, 1);
      }
    },
  },
};
</script>
<style scoped lang="scss"></style>
